/*

socket控制

*/

import {_getQuery} from '../../../tools'
import {_socketUrl} from '../../../api'
import Player from './player'
import State from './state'

let allPaiXing = {} // 所有玩家的牌型
let allScore = {} // 所有玩家的分数
let allPoker = {} // 所有玩家的牌
let ZhuangID = null // 本局庄家id
let tpList = [] // 每局已摊牌的列表

const SocketController = {
    // socket 对象
    socket: null,

    // 断开连接
    close: function () {
        this.socket.close()
    },

    // 初始化挂载socket对象
    init: function () {
        let room = _getQuery("room") // 房间号
        if (!room) {
            console.log("房间异常！")
            return
        }
        let socketUrl = _socketUrl(room) + '?token=' + localStorage.getItem('token') // socket地址
        this.socket = new WebSocket(socketUrl)
        this.socket.onopen = this.onopen
        this.socket.onmessage = this.onmessage
        this.socket.onclose = function (res) {
            console.log('---- close ----')
            console.log(res)
        }
    },

    // 打开 socket
    onopen: function (res) {
        console.log('----open----')
        console.log(res)
    },

    // 关闭 socket
    onclose: function (res) {
        console.log('----close----')
        console.log(res)
    },

    // 准备
    ready: function () {
        this.socket.send(JSON.stringify({
            messageCode: 1 
         }))
         State.target.prepare && State.target.prepare.destroy()
         State.target.prepare_text && State.target.prepare_text.destroy()
         State.target.stage.setText('等待其他玩家')
    },  

    // 抢庄
    rob: function (double) {
        SocketController.socket.send(JSON.stringify({
            messageCode: 2,
            qiangZhuangMultiple: double
         }))
         State.target.robButton && State.target.robButton.destroy()
    },
    rob0: function () { // 1 倍
        SocketController.rob(1)
    },
    rob1: function () { // 2 
        SocketController.rob(2)
    },
    rob2: function () { // 3
        SocketController.rob(3)
    },
    rob3: function () { // 不抢
        SocketController.rob(0)
    },

    // 下注
    bet: function (double) {
        SocketController.socket.send(JSON.stringify({
            messageCode: 3,
            xianJiaMultiple: double
         }))
         State.target.betButton && State.target.betButton.destroy()
    },
    bet0: function () {
        SocketController.bet(1)
    },
    bet1: function () {
        SocketController.bet(3)
    },
    bet2: function () {
        SocketController.bet(5)
    },
    bet3: function () {
        SocketController.bet(8)
    },

    // 看牌
    openmePoker: function () {
        tanpai(Player.players[0].id, true)
        State.target.showmeButton && State.target.showmeButton.destroy()
    },
    // 摊牌
    openPoker: function () {
        SocketController.socket.send(JSON.stringify({
            messageCode: 4
        }))
        State.target.showmeButton && State.target.showmeButton.destroy()
        State.target.showdownButton && State.target.showdownButton.destroy()
    },

    // 消息
    onmessage: function (res) {
        let d = JSON.parse(res.data)
        let r = d.data
        d.forEach(mm => {
            console.log("head:" + mm.head)
            console.log("status:" + mm.gameStatus)
            console.log(mm)
            console.log('-----------------')
            switch (mm.head) {
                // 玩家加入
                case 1000:
                    let index = Player.players.findIndex(r => r.id == mm.userId)
                    if (index < 0) {
                        index = Player.players.findIndex(r => r.status == 0);
                    }
                    Player.players[index].status = 1
                    Player.players[index].id = mm.userId
                    Player.players[index].info = {
                        avatarBorder: 'advatar_user',
                        avatar: mm.pictureUrl,
                        userName: mm.name,
                        score: mm.totalScore
                    }
                    Player.refresh()
                    break
                // 玩家掉线
                case 1001:
                    Player.players.forEach(e => {
                        if (e.id == mm.userId) {
                            e.status = 2
                        }
                    })
                    Player.refresh()
                    break
                // 准备阶段倒计时
                case 1002:
                    State.countDown(mm.countDown)
                    break
                // 某个玩家准备的消息，数据为准备玩家的id
                case 1003:
                    mm.readyPlayerIds.forEach(e => {
                        Player.players.forEach(p => {
                            if (p.id == e) {
                                p.ready = true
                            }
                        })
                    })
                    Player.refresh()
                    break

                // 发牌的消息
                case 1004:
                   
                    break
                // 抢庄倒计时
                case 1005:
                    State.countDown(mm.countDown)
                    State.target.stage.setText('开始抢庄')
                    break
                // 下注倒计时
                case 1007:
                    State.countDown(mm.countDown)
                    State.target.stage.setText('开始下注')
                    break
                // 摊牌倒计时
                case 1009:
                    State.countDown(mm.countDown)
                    State.target.stage.setText('摊牌阶段')
                    break

                // 有人抢庄
                case 1010:
                    let qz_index = Player.players.findIndex(e => e.id == mm.userId)
                    let num = Number(mm.qiangZhuangBeiShu) + 800
                    if (Number(mm.qiangZhuangBeiShu) == 0) {
                        num = 99
                    }
                    Player.showNiuNiu(qz_index, num)
                    break

                // 有人下注
                case 1011:
                    let xz_index = Player.players.findIndex(e => e.id == mm.userId)
                    Player.showNiuNiu(xz_index, Number(mm.xiaZhuBeiShu) + 800)
                    break

                // 有人摊牌
                case 1014:
                    tanpai(mm.userId)
                    break

                // 房间内情况，发给新人，数据为其他人的得分，牌，是否抢庄等
                case 2002:
                    console.log('------重连数据----')
                    Player.resetUser()
                    case1(mm)
                    resetReady(mm)
                    offlinePlayers(mm)
                    // 清除准备按钮
                    if (mm.gameStatus > 3) {
                        State.target.prepare && State.target.prepare.destroy()
                         State.target.prepare_text && State.target.prepare_text.destroy()
                    }
                    // 判断清除抢庄按钮
                    if (mm.gameStatus >= 5 && mm.gameStatus <=7) {
                        user_qz(mm)
                    }
                    // 发牌
                    if ((mm.gameStatus >= 4 && mm.gameStatus <= 12) || mm.gameStatus == 15) {
                        case4(mm)
                    }
                    // 庄家标志
                    if ((mm.gameStatus >= 7 && mm.gameStatus <= 12) || mm.gameStatus == 15) {
                        setTimeout(() => {
                            State.createMaster(Player.players.findIndex(e => e.id == mm.zhuangJiaUserId) - 1)
                        }, 50)
                    }
                    // 判断清除下注按钮
                    if (mm.gameStatus >= 8 && mm.gameStatus <= 10) {
                        user_xz(mm)
                    }
                    // 结算数据
                    if (mm.gameStatus == 15 || mm.gameStatus == 11 || mm.gameStatus ==12) {
                        allPaiXing = mm.paiXing
                        allScore = mm.scoreMap
                        allPoker = mm.userPokeMap_5
                        user_tp(mm)
                        // 已经摊牌的就开牌
                        if (mm.tanPaiPlayerUserIds) {
                            Player.players.forEach((p, i) => {
                                if (mm.tanPaiPlayerUserIds.indexOf(p.id.toString()) > -1) {
                                    let arr = mm.userPokeMap_5[p.id]
                                    let parr = []
                                    arr.forEach(e => {
                                        myPoker.parr(Player.transPoker(e))
                                    })
                                    Player.showPoker(i, parr)
                                }
                            })
                        }
                    }
                    return
            }


            switch (mm.gameStatus) {
                case '1': // 准备
                    case1(mm)
                    break
                case '2': // 准备倒计时开始
                    break
                case '3': // 准备倒计时结束
                    // State.openShow()
                    break
                case '4': // 发4张牌
                     State.openShow()
                    case4(mm)
                    break
                case '5': // 抢庄倒计时开始
                    State.robButton()
                    break
                case '6': // 抢庄倒计时结束
                    State.target.robButton && State.target.robButton.destroy()
                    break
                case '7': // 选择庄家，转圈的玩家id集合
                    let turnArr = []
                    ZhuangID = mm.userId
                    if (mm.zhuanQuanPlayers) {
                        Player.players.forEach((p, i) => {
                            if (mm.zhuanQuanPlayers.indexOf(p.id.toString()) > -1) {
                                turnArr.push(i - 1)
                            }
                        })
                    } else {
                        turnArr.push(Player.players.findIndex(e => e.id == mm.userId) - 1) 
                    }
                    let index = 0
                    let turn = setInterval(() => {
                        State.createMaster(turnArr[index])
                        index++
                        if (index == turnArr.length) {
                            index = 0
                        }
                    }, 100)
                    setTimeout(() => {
                        clearInterval(turn)
                        State.createMaster(Player.players.findIndex(e => e.id == mm.userId) - 1)
                    }, 2000)
                    break
                case '8': // 闲家下注倒计时开始
                    State.target.stage.setText('开始下注')
                    State.target.countDown && State.target.countDown.destroy()
                    if (ZhuangID != Player.players[0].id) {
                        State.betButton()
                    }
                    break
                case '9': // 闲家下注倒计时结束
                    State.target.betButton && State.target.betButton.destroy()
                    break
                case '10': // 默认下注
                    break
                case '11': // 摊牌倒计时开始
                    State.target.stage.setText('摊牌阶段')
                    State.target.countDown && State.target.countDown.destroy()
                    State.showdownButton()
                    State.showmeButton()
                    break
                case '12': // 摊牌倒计时结束
                    State.target.showdownButton && State.target.showdownButton.destroy()
                    State.target.showmeButton && State.target.showmeButton.destroy()
                    Player.players.forEach(e => {
                        if (e.id && tpList.indexOf(e.id.toString()) < 0) {
                            tanpai(e.id)
                        }
                    })
                    break
                case '13': // 本局结算
                    State.target.stage.setText('本局结算')
                    State.target.countDown && State.target.countDown.destroy()
                    // 结算动画
                    Player.players.forEach(e => {
                        for (let i in allScore) {
                            if (e.id == i) {
                                e.info.score = Number(e.info.score) + Number(allScore[i])
                                setTimeout(() => {
                                    State.changeScoreAni(Player.players.findIndex(pp => pp.id == i), Number(allScore[i]))
                                }, 1200)
                            }
                        }
                    })
                    Player.refresh()
                    setTimeout(() => {
                        State.target.stage.setText('未准备')
                        State.target.master && State.target.master.destroy()
                        Player.players.forEach(e => {
                            e.pokers && e.pokers.destroy()
                        })
                        State.createPrepare()
                    }, 3000)


                    // 回滚状态
                    tpList = []
                    break
                case '14': // 结束
                    
                    break
                case '15': // 发一张牌
                    allPaiXing = mm.paiXing
                    allScore = mm.scoreMap
                    allPoker = mm.userPokeMap_5
                    break
            }
        })
    }

}


function tanpai (userId, dis_voice) {
    let tpArr = []
    tpList.push(userId)
    allPoker[userId].forEach(e => {
        tpArr.push(Player.transPoker(e))
    })
    let i = Player.players.findIndex(e => e.id == userId)
    Player.showPoker(i, tpArr)
    if (!dis_voice) { // 如果是看牌
        Player.showNiuNiu(i, allPaiXing[userId] + 60)
    }
}


// 准备阶段
function case1 (mm) {
    // 自己的信息
    Player.players[0].status = 1
    Player.players[0].id = mm.userId
    Player.players[0].info = {
        avatarBorder: 'advatar_user',
        avatar: mm.pictureUrl,
        userName: mm.name,
        score: mm.totalScore
    }
    if (mm.readyPlayerIds && mm.readyPlayerIds.indexOf(mm.userId.toString()) > -1) {
        Player.players[0].ready = true
        State.target.prepare && State.target.prepare.destroy()
        State.target.prepare_text && State.target.prepare_text.destroy()
        State.updateStage('已准备')
    }
    // 其他人
    mm.players.forEach(p => {
        if (p.userId != mm.userId) {
            let index = index = Player.players.findIndex(r => r.status == 0);
            console.log(index)
            Player.players[index].status = 1
            Player.players[index].id = p.userId
            if (mm.readyPlayerIds && mm.readyPlayerIds.indexOf(p.userId.toString()) > -1) {
                Player.players[index].ready = true
            }
            Player.players[index].info = {
                avatarBorder: 'advatar_user',
                avatar: p.pictureUrl,
                userName: p.name,
                score: p.totalScore
            }
        }
    })

    Player.refresh()
    // 房间信息
    let roomInfo = mm.runingAndTotal.split('/')
    State.updateRoundText(roomInfo[0], roomInfo[1])
}

// 重置准备信息
function resetReady (mm) {
    mm.readyPlayerIds && mm.readyPlayerIds.forEach(e => {
        Player.players.forEach(p => {
            if (e == p.id) {
                p.ready = true
            }
        })
    })
}

// 判断当前玩家是否已经抢庄
function user_qz (mm) {
    let key = false
    State.robButton()
    if (mm.qiangZhuangMap) {
        for (let key in mm.qiangZhuangMap) {
            if (Player.players[0].id == mm.qiangZhuangMap[key]) {
                key = true
            }
        }
    }
    if (key) {
        setTimeout(() => {
            State.target.robButton && State.target.robButton.destroy()
        }, 100)
    }
}

// 判断当前玩家是否已经下注
function user_xz (mm) {
    let key = false
    State.betButton()
    if (mm.xianJiaXiaZhuMap) {
        for (let key in mm.xianJiaXiaZhuMap) {
            if (Player.players[0].id == mm.xianJiaXiaZhuMap[key]) {
                key = true
            }
        }
    }
    if (key) {
        setTimeout(() => {
            State.target.betButton && State.target.betButton.destroy()
        }, 100)
    }
}

// 判断当前玩家是否已经摊牌
function user_tp (mm) {
    let key = false
    State.showdownButton()
    if (mm.tanPaiPlayerUserIds) {
        for (let key in mm.tanPaiPlayerUserIds) {
            if (Player.players[0].id == mm.tanPaiPlayerUserIds[key]) {
                key = true
            }
        }
    }
    if (key) {
        setTimeout(() => {
            State.target.showdownButton && State.target.showdownButton.destroy()
        }, 100)
    }
}

// 重连之后渲染掉线玩家
function offlinePlayers (mm) {
    mm.disConnectionPlayerIds.length && Player.players.forEach(e => {
        if (mm.disConnectionPlayerIds.indexOf( e.id.toString() ) > -1 ) {
            e.status = 2
        }
    })
    Player.refresh()
}

function case4 (mm) {
    setTimeout(() => {
        Player.players.forEach((e, i) => {
            if (e.ready) {
                Player.pokerPlayer(i)
            }
        })
        let myPoker = []
        mm.userPokeList_4 && mm.userPokeList_4.forEach(e => {
            myPoker.push(Player.transPoker(e))
        })
        mm.userPokeList_5 && mm.userPokeList_5.forEach(e => {
            myPoker.push(Player.transPoker(e))
        })
        mm.userPokeList_5 && myPoker.pop()
        if (mm.userPokeMap_5) {
            let mid = Player.players[0].id
            mm.userPokeMap_5[mid].forEach(e => {
                myPoker.push(Player.transPoker(e))
            })
            myPoker.pop()
        }
        myPoker.push(54)
        console.log('myPoker')
        console.log(myPoker)
        setTimeout(() => {
            Player.showPoker(0, myPoker)
        }, 1000)
    
        // State.target.stage.setText('开始抢庄')
        Player.players.forEach(e => {
            e.ready = false
        })
        Player.refresh()
        State.target.countDown && State.target.countDown.destroy()
    })
}

export default SocketController